﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Snom
{
    class EventsManager
    {
        public event SnomGenericEventHandler EventArrived;
        public event ErrorEventHandler Error;

        private EventsRegistration _eventsRegistration;
        private EventsHttpListener _eventsHttpListener;

        public EventsManager(string phoneIpAddress, string username, string password, int listeningPort)
        {
            _eventsRegistration = new EventsRegistration(phoneIpAddress, username, password, listeningPort);
            _eventsRegistration.Register();

            _eventsHttpListener = new EventsHttpListener(listeningPort);
            _eventsHttpListener.EventArrived += new SnomGenericEventHandler(EventsHttpListener_EventArrived);
            _eventsHttpListener.Error += new ErrorEventHandler(EventsHttpListener_Error);
            _eventsHttpListener.Start();
        }

        private void EventsHttpListener_Error(object sender, ErrorEventArgs e)
        {
            RaiseError(e.Error);
        }

        private void EventsHttpListener_EventArrived(object sender, SnomGenericEventArgs e)
        {
            if (EventArrived != null)
            {
                EventArrived(this, e);
            }
        }

        private void RaiseError(Exception error)
        {
            if (Error != null)
            {
                Error(this, new ErrorEventArgs(error));
            }
        }

        public int ListeningPort
        {
            get
            {
                return _eventsHttpListener.HttpServerPort;
            }
        }

        public void UnregisterEvents()
        {
            _eventsRegistration.Unregister();
        }

    }
}
